//
//  DZYContentView.swift
//  DZYPageView
//
//  Created by dongzhenyu on 2017/7/6.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit

private let contnetCellID = "contnetCellID"

protocol DZYContentViewDelegate: class {
    func contentView(_ contentView: DZYContentView, didEndScroll inIndex: Int)
    func contentView(_ contentView: DZYContentView, soureIndex: Int, targetIndex: Int, progress: CGFloat)
    
}

class DZYContentView: UIView {

    // MARK: - 属性
    weak var delegate: DZYContentViewDelegate?
    
    fileprivate var childVcs: [UIViewController]
    fileprivate var parentVc: UIViewController
    fileprivate var startOffsetX: CGFloat = 0
    fileprivate var isForbidDelegate: Bool = false // 是否禁止调用代理
//    fileprivate lazy var collectionView: UICollectionView = UICollectionView(frame: self.bounds, collectionViewLayout: UICollectionViewFlowLayout())
    fileprivate lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = self.bounds.size
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout:layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false // 第一个和最后一个cell去掉弹簧效果
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contnetCellID)
        
        return collectionView
    }()
    
    // MARK: - 构造方法
    init(frame: CGRect, childVcs: [UIViewController] , parentVc: UIViewController) {
        self.childVcs = childVcs
        self.parentVc = parentVc
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - 设置UI界面
extension DZYContentView {

    fileprivate func setupUI() {
    
        // 1.将childVcs中所有控制器添加到parentVc中
        for childVc in childVcs {
            parentVc.addChildViewController(childVc)
        }
        
        // 2.
        addSubview(collectionView)
    }
}

// MARK: - UICollectionView 协议
extension DZYContentView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        // 获取cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contnetCellID, for: indexPath)
        
        // 添加内容
        // 删除之前的 避免重复添加
        for subview in cell.contentView.subviews {
            subview.removeFromSuperview()
        }
        
        // 将对应的控制器的view添加到cell中
        let childVc = childVcs[indexPath.item]
        cell.contentView.addSubview(childVc.view)
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item)
    }
    
}

// MARK: - 遵守UICollectionViewDelegate 协议
extension DZYContentView: UICollectionViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewDidEndScroll()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            scrollViewDidEndScroll()
        }
    }
    
    private func scrollViewDidEndScroll() {
        let index = Int(collectionView.contentOffset.x / collectionView.bounds.width)
        
        delegate?.contentView(self, didEndScroll: index)
    }
    
    // 只要一拖动就会调用
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isForbidDelegate = false
        startOffsetX = scrollView.contentOffset.x
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let contentOffsetX = scrollView.contentOffset.x
        // 判断有没有滑动
        guard contentOffsetX != startOffsetX && !isForbidDelegate else {
            return
        }
        
        // 定义出需要的变量
        var sourceIndex = 0
        var targetIndex = 0
        var progress: CGFloat = 0
        
        // 获取需要的参数
        let collectionWidth = collectionView.bounds.width
        if contentOffsetX > startOffsetX { // 左滑动
            sourceIndex = Int(contentOffsetX / collectionWidth)
            targetIndex = sourceIndex + 1
            
            if targetIndex >= childVcs.count {
                targetIndex = childVcs.count - 1
            }
            
            progress = (contentOffsetX - startOffsetX) / collectionWidth
            
            if contentOffsetX - startOffsetX == collectionWidth {
                targetIndex = sourceIndex
            }
            
            
        } else {
            targetIndex = Int(contentOffsetX / collectionWidth)
            sourceIndex = targetIndex + 1
            progress = (startOffsetX - contentOffsetX) / collectionWidth
        }
        
//        print("sourceIndex:\(sourceIndex) targetIndex:\(targetIndex) progress:\(progress)")
        
        delegate?.contentView(self, soureIndex: sourceIndex, targetIndex: targetIndex, progress: progress)
    }
    
}

// MARK: - 遵守DZYTitleViewDelegate 协议
extension DZYContentView: DZYTitleViewDelegate {
    
    func titleView(_ titleView: DZYTitleView, targetIndex: Int) {
        print(targetIndex)
        
        // 0. 点击的时候禁止代理
        isForbidDelegate = true
        
        // 1.根据index 创建indexPath
        let indexPath = IndexPath(item: targetIndex, section: 0)
        
        // 2.滚动到正确的位置
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
    }
}




